package com.sz.netty.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.service.IService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.sz.netty.entity.DtuFtpInfo;
import com.sz.netty.mapper.NettyDtuFtpInfoMapper;
import com.sz.netty.service.DtuFtpInfoService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * DTU FTP设备连接信息服务实现类
 */
@Service
public class NettyDtuFtpInfoServiceImpl extends ServiceImpl<NettyDtuFtpInfoMapper, DtuFtpInfo> implements DtuFtpInfoService {
    
    @Override
    public DtuFtpInfo saveDtuFtpInfo(DtuFtpInfo dtuFtpInfo) {
        // 设置创建时间和更新时间
        Date now = new Date();
        if (dtuFtpInfo.getCreateTime() == null) {
            dtuFtpInfo.setCreateTime(now);
        }
        dtuFtpInfo.setUpdateTime(now);
        
        // 设置删除标志默认值
        if (dtuFtpInfo.getDelFlag() == null) {
            dtuFtpInfo.setDelFlag("F");
        }
        
        // 保存到数据库
        this.save(dtuFtpInfo);
        return dtuFtpInfo;
    }
    
    @Override
    public DtuFtpInfo getOne(QueryWrapper queryWrapper) {
        return super.getOne(queryWrapper);
    }
    
    @Override
    public int updateDisconnectInfoByChannelId(String channelId, Date disconnectTime) {
        // Create update entity
        DtuFtpInfo updateEntity = new DtuFtpInfo();
        updateEntity.setDisconnectTime(disconnectTime);
        updateEntity.setStatus(0); // Set status to offline
        updateEntity.setUpdateTime(new Date());
        
        // Update records with matching channel ID and status=1 (online)
        boolean result = this.update(updateEntity, 
            new QueryWrapper()
                .where("channel_id = ?", channelId)
                .and("status = ?", 1));
        
        // Return 1 if update was successful, 0 otherwise
        return result ? 1 : 0;
    }
}